package com.llcbenwu.filter;


import com.llcbenwu.code.SmsCode;
import com.llcbenwu.controller.VerificationCodeController;
import com.llcbenwu.exception.ValidateCodeException;
import com.llcbenwu.security.SecurityProperies;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 自定义过滤器
 * OncePerRequestFilter保证每次验证只调一次
 * @author lilinchun
 * @date 2021/10/26 0026 15:09
 */
@Data
public class VerificationFilter extends OncePerRequestFilter {

    /**
     * 自定义异常
     */
    private AuthenticationFailureHandler authenticationFailureHandler;

    /**
     * session
     */
    private SessionStrategy sessionStrategy=new HttpSessionSessionStrategy();

    /**
     * 过滤url
     * @return
     */
    private Set<String> urls=new HashSet<>();

    /**
     * 路径匹配
     */
    private AntPathMatcher antPathMatcher=new AntPathMatcher();



    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {


        System.out.println(request.getRequestURI()+"============="+request.getMethod());
        if(StringUtils.isNotBlank(SecurityProperies.URL)){
            String[] split = SecurityProperies.URL.split(",");
            urls = Arrays.stream(split).collect(Collectors.toSet());
            System.out.println("urls:"+urls.toString());
           boolean flag=false;
           for (String ulr:urls){
               if(antPathMatcher.match(ulr,request.getRequestURI())){
                   flag=true;
               }
           }
            if(flag) {
                try {
                    validate(new ServletWebRequest(request));
                } catch (ValidateCodeException e) {
                    System.out.println(e.getMessage());
                    authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                    return;
                }
            }

        }

        filterChain.doFilter(request,response);
    }

    /**
     * 检验
     * @param request
     */
    private void validate(ServletWebRequest request) throws ServletRequestBindingException {
//     ImageCode imageCode= (ImageCode) sessionStrategy.getAttribute(request, VerificationCodeController.SESSION_KEY);
        SmsCode imageCode= (SmsCode) sessionStrategy.getAttribute(request, VerificationCodeController.SESSION_KEY);
        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "imageCode");
        System.out.println("imageCode:"+imageCode);
        if (StringUtils.isBlank(codeInRequest)){
            throw new ValidateCodeException("验证码的值不能为空");
        }
        if(imageCode==null){
            throw  new ValidateCodeException("验证码不存在");

        }
        if(imageCode.isExpried()){
            sessionStrategy.removeAttribute(request,VerificationCodeController.SESSION_KEY);
            throw  new ValidateCodeException("验证码已过期");
        }
        if(!StringUtils.equals(imageCode.getCode(),codeInRequest)){
            throw  new ValidateCodeException("验证码不匹配");
        }

        sessionStrategy.removeAttribute(request,VerificationCodeController.SESSION_KEY);
    }
}
